/*
    @params function
    类似计算属性 / 缓存函数
    @return new function
*/
function cacheMemo(fun) {
  const objMemo = Object.create(null)
  return function(...args) {
    const _arg = JSON.stringify(args)
    return objMemo[_arg] || (objMemo[_arg] = fun.apply(fun, args))
  }
}

/*
    @params 任意变量
    深度克隆
    @return new 变量
*/
function cloneUtil(target) {
  const type = Object.prototype.toString.call(target)
  let res
  if (typeof target !== 'object') {
    return target
  } else if (typeof target === 'object') {
    if (type.includes('Object')) {
      res = {}
    } else if (type.includes('Array')) {
      res = []
    }
  } else {
    return
  }
  for (const key in target) {
    if (typeof target[key] === 'object') {
      res[key] = cloneUtil(target[key])
    } else {
      res[key] = target[key]
    }
  }
  return res
}
/*
  日期格式化
*/
function formatDate(date, fmt) {
  // 获取年份
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  // 获取m+ d+ h+ m+ s+
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}

function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}
/*
  防抖
*/
function debounce(fun, delay) {
  let timer = null
  return (...args) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun.apply(fun, args)
    }, delay)
  }
}
export default {
  cacheMemo,
  cloneUtil,
  formatDate,
  debounce
}
